var _util = require('../../util/util.js')
const _main_service = require('../../service/main_service.js')
const _cart_service = require('../../service/cart_service.js')
require('./index.css')

// 获取存储在 localStorage 中的用户信息
const userInfo = localStorage.getItem('userInfo');
const user = JSON.parse(userInfo);

$(document).on('click', '.sale-btn', function () {
  localStorage.setItem('fromCart', 0);
  console.log('fromCart is set to 0...');
});

//购物车结算
$('a.btn.btn-primary.btn-cart').on('click', function () {
  localStorage.setItem('fromCart', 1);
})

const ShoppingCart = {
  init: function () {


    if (userInfo) {
      this.checkLoginAndLoadCart(user);  // 检查用户登录状态并加载购物车
    } else {
      console.log("没有找到用户信息，用户未登录");
    }

    const itemStr = localStorage.getItem("selectedItem");
    if (!itemStr) {
      $("#cart-container").html("<p>未找到商品信息</p>");
      return;
    }

    const item = JSON.parse(itemStr);
    console.log(item)
    const templateText = $("#cart-template").html();

    // 使用 _util.renderHTML 方法进行模板渲染
    const html = _util.renderHTML(templateText, item);

    this.bindEvent();

    $("#cart-container").html(html);
  },

  bindEvent: function () {
    const _this = this;

    _main_service.getHomepageData(function (data) {
      _this.renderHeader(data); // 渲染头部
    }, function (errMsg) {
      _util.errorTips('首页加载失败：' + errMsg);  // 错误提示
    });

    // 监听搜索事件
    $('#searchButton').click(function () {
      _this.searchItem();
    });

  },

  renderHeader: function (data) {
    const headerTemplate = $('#header-template').html();
    const html = _util.renderHTML(headerTemplate, data);
    $('.header-nav .nav-list').html(html);

    $('#addToCart').click((event) => {
      let itemId = $(event.currentTarget).data("item"); // 用 jQuery 的 data() 方法获取 data-item

      _util.request({
        method: "GET",
        url: _util.getServerURL(`cart/${itemId}?userId=${user.id}`),
        contentType: "application/json",
        dataType: "json",
        data: null,
        success: function (data, msg) {
          alert("商品已成功加入购物车！");
          window.location.href = "/view/user_main.html";
        },
        error: function (msg) {
          alert(msg || "添加购物车失败，请稍后再试！");
        }
      });
    });
  },

  // 检查用户登录状态并加载购物车
  async checkLoginAndLoadCart(user) {
    try {
      await this.renderUserInfo(user);
      if (user) {
        await this.loadCartData();
      } else {
        $('#topBarItemCount').text('（0）');
      }
    } catch (err) {
      console.error('获取用户登录信息失败:', err);
      $('#topBarItemCount').text('（0）');
    }
  },

  // 获取用户信息并渲染
  async renderUserInfo(user) {
    try {
      if (user && user.username) {
        $("#loggedInSection").show();
        $("#notLoggedInSection").hide();

        $("#welcomeUser").text(`欢迎回来！${user.username}`);
        $("#username").val(user.username || "");
        $("#email").val(user.email || "");
        $("#age").val(user.age || "");
      } else {
        $("#loggedInSection").hide();
        $("#notLoggedInSection").show();
      }

      return user;
    } catch (error) {
      console.error("获取用户信息失败：", error);
      $("#loggedInSection").hide();
      $("#notLoggedInSection").show();

      return null;
    }
  },

  // 显示搜索结果
  displaySearchResults: function (results) {
    const resultsContainer = $('#J_keywordList');
    const resultList = resultsContainer.find('.result-list');
    resultList.empty();

    if (results.length > 0) {
      resultsContainer.show();
      results.forEach(function (item) {
        const li = $('<li>');
        const a = $('<a>', {
          text: item.name,
          href: "javascript:void(0);", // 防止跳转
          click: function () { goToCart(this); }, // 绑定点击事件
          'data-id': item.id,
          'data-name': item.name,
          'data-price': item.price,
          'data-description': item.description,
          'data-url': item.url
        });
        li.append(a);
        resultList.append(li);
      });
    } else {
      resultsContainer.hide();
      resultList.append('<li>没有找到相关商品</li>');
    }
  },

  // 搜索商品
  searchItem: function () {
    var query = $('#search').val().trim();
    if (query.length < 1) {
      $('#J_keywordList').hide();
      return;
    }

    _util.fetch(_util.getServerURL("/search"), {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ key: query })
    })
      .then(response => response.json())
      .then(results => {
        this.displaySearchResults(results);
      })
      .catch(error => {
        console.error("搜索请求出错：", error);
      });
  },

  // 加载购物车数据
  async loadCartData() {
    _cart_service.getCartData(
      user.id,
      function (cart) {
        console.log(cart.itemList);
        // === 成功回调 ===
        const $cartContainer = $('#cartContainer');
        const $list = $('#J_miniCartList');
        const $totalCount = $('#CartListTotalCount');
        const $totalPrice = $('#CartListTotalPrice');
        const $itemCount = $('#topBarItemCount');
        const $emptyCart = $('#emptyCart');

        $list.empty();

        if (cart && cart.totalCount > 0) {
          $cartContainer.show();
          $emptyCart.hide();

          cart.itemList.forEach(item => {
            const $li = $(`
                          <li class="cart-item" data-item-id="${item.itemID}">
                            <div class="clearfix first">
                              <a class="thumb" href="${item.url}">
                                <img alt="${item.name}" src="${item.url}">
                              </a>
                              <span class="name">${item.name}</span>
                              <span class="price Item-price">${item.price}</span>
                              <div class="count-control">
                                <button class="count_d">-</button>
                                <span class="price Item-count">${item.itemNum}</span>
                                <button class="count_i">+</button>
                              </div>
                              <a class="btn-del J_delItem"><em class="iconfont-close"></em></a>
                            </div>
                          </li>
                        `);
            $list.append($li);
          });

          $totalCount.text(cart.totalCount);
          $totalPrice.text(cart.totalPrice);
          $itemCount.text(`（${cart.totalCount}）`);

          let cartList = document.getElementById("J_miniCartList");
          if (cartList) {
            let cartItems = cartList.children;
            console.log(cartItems);
            let currentCartListTotalCount = parseInt($('#CartListTotalCount').text());
            let currentCartListTotalPrice = parseInt($('#CartListTotalPrice').text());
            if (cartItems && cartItems.length > 0) {
              for (let cartItem of cartItems) {
                console.log(cartItem);
                let i_btn = cartItem.querySelector(".count_i");
                let d_btn = cartItem.querySelector(".count_d");
                let itemCount = cartItem.querySelector(".Item-count");
                let itemPrice = cartItem.querySelector(".Item-price");
                let currentCount = parseInt(itemCount.textContent);
                let ItemPrice = parseInt(itemPrice.textContent);
                let itemId = cartItem.getAttribute('data-item-id');
                let delBtn = cartItem.querySelector('.btn-del');
                // **删除商品**
                delBtn.addEventListener("click", async (event) => {
                  let result = confirm("确定删除吗?");
                  if (!result) return;
                  _cart_service.removeItem(
                    user.id,
                    itemId,
                    function () {
                      console.log("删除成功");
                      alert("删除成功");

                      currentCartListTotalCount -= currentCount;
                      currentCartListTotalPrice -= ItemPrice * currentCount;

                      $('#topBarItemCount').text(`(${currentCartListTotalCount})`);

                      if (currentCartListTotalCount > 0) {
                        cartList.removeChild(event.target.closest('li'));
                        $('#CartListTotalCount').text(currentCartListTotalCount);
                        $('#CartListTotalPrice').text(currentCartListTotalPrice);
                      } else {
                        $('#J_miniCartList').html('');
                        $('#J_miniCartListTotal').html('<div class="msg msg-empty">购物车中还没有商品，赶紧选购吧！</div>');
                      }
                    },
                    function (error) {
                      console.error("删除失败", error);
                      alert("删除失败");
                    }
                  );
                });
                // **增加商品数量**
                i_btn.addEventListener("click", () => {
                  console.log("+1")
                  currentCount++;
                  currentCartListTotalCount++;
                  currentCartListTotalPrice += ItemPrice;
                  itemCount.textContent = String(currentCount);
                  $('#CartListTotalCount').text(currentCartListTotalCount);
                  $('#CartListTotalPrice').text(currentCartListTotalPrice);
                  $('#topBarItemCount').text(`(${currentCartListTotalCount})`);
                  updateDatabase(itemId, currentCount);
                });
                // **减少商品数量**
                d_btn.addEventListener("click", async (event) => {
                  console.log("-1")
                  currentCount--;
                  currentCartListTotalCount--;
                  currentCartListTotalPrice -= ItemPrice;
                  if (currentCount === 0) {
                    let result = confirm("本次操作将从购物车移除此商品，确定删除吗?");
                    if (!result) {
                      currentCount++;
                      currentCartListTotalCount++;
                      currentCartListTotalPrice += ItemPrice;
                      return;
                    }
                    $('#topBarItemCount').text(`(${currentCartListTotalCount})`);
                    _cart_service.removeItem(
                      user.id,
                      itemId,
                      function () {
                        console.log("删除成功");
                        cartList.removeChild(event.target.closest('li'));
                        $('#CartListTotalCount').text(currentCartListTotalCount);
                        $('#CartListTotalPrice').text(currentCartListTotalPrice);

                        if (currentCartListTotalCount === 0) {
                          $('#J_miniCartList').html('');
                          $('#J_miniCartListTotal').html('<div class="msg msg-empty">购物车中还没有商品，赶紧选购吧！</div>');
                        }
                      },
                      function (error) {
                        console.error("删除失败", error);
                        alert("删除失败");

                        currentCount++;
                        currentCartListTotalCount++;
                        currentCartListTotalPrice += ItemPrice;
                      }
                    );
                  } else {
                    itemCount.textContent = String(currentCount);
                    $('#CartListTotalCount').text(currentCartListTotalCount);
                    $('#CartListTotalPrice').text(currentCartListTotalPrice);
                    $('#topBarItemCount').text(`(${currentCartListTotalCount})`);
                    updateDatabase(user.id, itemId, currentCount);
                  }
                });
              }
            }
          }
        } else {
          $cartContainer.show();
          $emptyCart.show();
          $itemCount.text('（0）');
        }
      },
      function (err) {
        // === 失败回调 ===
        console.error('加载购物车失败:', err);
      }
    );
  },
};

$(function () {
  ShoppingCart.init();
})

$('.link').on('mouseenter', function () {
  // 显示购物车弹出层
  $('#J_miniCartMenu').css('height', 'auto');

  // 加载购物车数据
  user_main.loadCartData();
});

$('#cartContainer').on('mouseleave', function () {
  $('#J_miniCartMenu').css('height', '0');
});

const updateDatabase = (itemID, count) => {
  _cart_service.updateCart(user.id, itemID, count,
    function (res) {
      console.log("数量更新成功", res);
    },
    function (err) {
      console.error("数量更新失败", err);
    }
  );
};

goToCart = function (el) {
  // 获取当前 item 的父元素
  const $img = $(el).find("img.thumbImg");
  if ($img.length === 0) return;

  const item = {
    id: $img.data("id") || '',
    name: $img.data("name") || '',
    price: $img.data("price") || '',
    description: $img.data("description") || '',
    url: $img.attr("src") || ''
  };

  localStorage.setItem("selectedItem", JSON.stringify(item));
  window.location.href = "/view/ShoppingCart.html";
};

goToCart = function (el) {
  const $a = $(el);
  const item = {
    id: $a.data("id") || '',
    name: $a.data("name") || '',
    price: $a.data("price") || '',
    description: $a.data("description") || '',
    url: $a.data("url") || ''
  };

  localStorage.setItem("selectedItem", JSON.stringify(item));
  window.location.href = "/view/ShoppingCart.html";
}
